package top.huahaizhi.zhihu.daily.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.List;
import java.util.Locale;

import butterknife.BindString;
import butterknife.BindView;
import top.huahaizhi.zhihu.daily.BaseActivity;
import top.huahaizhi.zhihu.daily.K;
import top.huahaizhi.zhihu.daily.R;
import top.huahaizhi.zhihu.daily.bean.StoryDetailBean;
import top.huahaizhi.zhihu.daily.util.NetUtils;

public class DetailActivity extends BaseActivity {

    private int storyId = -1;

    @BindString(R.string.app_name)
    String storyTitle;

    @BindView(R.id.wv_detail_story)
    WebView webView;
    @BindView(R.id.swipeRoot)
    SwipeRefreshLayout rootView;

    private StoryDetailBean story;

    @Override
    protected boolean isStatusBar() {
        return false;
    }

    @Override
    public int getLayoutId(Bundle savedInstanceState) {
        return R.layout.activity_detail;
    }

    @Override
    protected void initData() {
        super.initData();
        storyId = getIntent().getIntExtra(K.STORY_ID_KEY, -1);
        storyTitle = getIntent().getStringExtra(K.STORY_TITLE_KEY);
        if (storyId == -1) {
            finish();
            return;
        }
        if (TextUtils.isEmpty(storyTitle))
            storyTitle = getString(R.string.app_name);
        initWebViewSettings();
    }

    @Override
    protected void setParams() {
        super.setParams();
        rootView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                accessNet();
            }
        });
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(storyTitle);
            getSupportActionBar().setElevation(3f);
        }
    }

    @Override
    protected void accessNet() {
        super.accessNet();
        rootView.setRefreshing(true);
        NetUtils.getInstance(this).go(K.DETAIL_URL + storyId, new NetUtils.OnRequestListener<String>() {
            @Override
            public void onSuccess(String object) {
                rootView.setRefreshing(false);
                story = new Gson().fromJson(object, StoryDetailBean.class);
//                webView.loadData(storyDetailBean.getBody(),"text/html", "gb2312"); 如果这样写会乱码
                String html = getHtml(story.getJs(), story.getCss(), story.getBody(), story.getImage());
                webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
            }

            @Override
            public void onFail(String reason) {
                rootView.setRefreshing(false);
                Toast.makeText(DetailActivity.this, reason, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String getHtml(List<String> jsList, List<String> cssList, String body, String img) {
        //组合js字符串
        String jsResult = "";
        for (String jsItem : jsList)
            jsResult = jsResult + "\n" + String.format("<script src=\"%s\"/>", jsItem);
        //组合css字符串
        String cssResult = "";
        for (String cssItem : cssList)
            cssResult = cssResult + "\n" + String.format("<link href=\"%s\" rel=\"stylesheet\"/>", cssItem);
        //组合整个Html
        return String.format(Locale.CHINA, "<html>\n" +
                "            <head>\n" +
                "\t        <meta charset=\"utf-8\"/>\n" +
                "        \t<meta name=\"viewport\" content=\"width=device-width,user-scalable=no\"/>\n" +
                "                %s\n" +
                "                %s\n" +
                "            </head>\n" +
                "            %s\n" +
                "        </html>", jsResult, cssResult, body.replace("<div class=\"img-place-holder\"></div>", ""));
    }

    private void initWebViewSettings() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setData(Uri.parse(story.getShare_url()));
        shareIntent.putExtra(Intent.EXTRA_TITLE, story.getTitle());
        shareIntent.putExtra(Intent.EXTRA_TEXT, story.getBody());
        startActivity(Intent.createChooser(shareIntent, story.getTitle()));
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        BitmapDrawable drawable = new BitmapDrawable(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.ic_share_black_24dp));
        menu.add("分享").setIcon(drawable);
        return true;
    }
}